package com.carrental.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.user.dto.UserInfoDTO;
import com.carrental.user.entity.UserInfo;
import com.carrental.user.mapper.UserInfoMapper;
import com.carrental.user.service.UserInfoService;
import com.carrental.user.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户信息服务实现类
 */
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    /**
     * 根据用户ID获取用户信息
     *
     * @param userId 用户ID
     * @return 用户信息VO
     */
    @Override
    public UserInfoVO getUserInfoByUserId(Long userId) {
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId)
                .eq(UserInfo::getDeleted, 0));
        
        if (userInfo == null) {
            return null;
        }
        
        return convertToVO(userInfo);
    }

    /**
     * 保存或更新用户信息
     *
     * @param userInfoDTO 用户信息DTO
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateUserInfo(UserInfoDTO userInfoDTO) {
        if (userInfoDTO.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userInfoDTO.getUserId())
                .eq(UserInfo::getDeleted, 0));
        
        if (userInfo == null) {
            // 新增
            userInfo = new UserInfo();
            BeanUtils.copyProperties(userInfoDTO, userInfo);
            userInfo.setUserLevel(0); // 默认普通用户
            userInfo.setPoints(0);    // 默认积分为0
            userInfo.setCreditScore(100); // 默认信用分为100
            userInfo.setCreateTime(LocalDateTime.now());
            userInfo.setUpdateTime(LocalDateTime.now());
            userInfo.setDeleted(0);
            return save(userInfo);
        } else {
            // 更新
            BeanUtils.copyProperties(userInfoDTO, userInfo);
            userInfo.setUpdateTime(LocalDateTime.now());
            return updateById(userInfo);
        }
    }

    /**
     * 分页查询用户信息
     *
     * @param page     分页参数
     * @param userInfo 查询条件
     * @return 分页结果
     */
    @Override
    public Page<UserInfoVO> pageUserInfo(Page<UserInfo> page, UserInfo userInfo) {
        Page<UserInfo> userInfoPage = page(page, new LambdaQueryWrapper<UserInfo>()
                .eq(userInfo.getUserId() != null, UserInfo::getUserId, userInfo.getUserId())
                .like(userInfo.getRealName() != null, UserInfo::getRealName, userInfo.getRealName())
                .like(userInfo.getMobile() != null, UserInfo::getMobile, userInfo.getMobile())
                .eq(userInfo.getUserLevel() != null, UserInfo::getUserLevel, userInfo.getUserLevel())
                .eq(UserInfo::getDeleted, 0)
                .orderByDesc(UserInfo::getCreateTime));
        
        Page<UserInfoVO> userInfoVOPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<UserInfoVO> userInfoVOList = new ArrayList<>();
        
        for (UserInfo info : userInfoPage.getRecords()) {
            userInfoVOList.add(convertToVO(info));
        }
        
        userInfoVOPage.setRecords(userInfoVOList);
        return userInfoVOPage;
    }

    /**
     * 增加用户积分
     *
     * @param userId 用户ID
     * @param points 积分
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addPoints(Long userId, Integer points) {
        if (points <= 0) {
            throw new BusinessException("积分必须大于0");
        }
        
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId)
                .eq(UserInfo::getDeleted, 0));
        
        if (userInfo == null) {
            throw new BusinessException("用户不存在");
        }
        
        userInfo.setPoints(userInfo.getPoints() + points);
        userInfo.setUpdateTime(LocalDateTime.now());
        
        // 根据积分更新用户等级
        updateUserLevelByPoints(userInfo);
        
        return updateById(userInfo);
    }

    /**
     * 更新用户信用分
     *
     * @param userId      用户ID
     * @param creditScore 信用分
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCreditScore(Long userId, Integer creditScore) {
        if (creditScore < 0 || creditScore > 100) {
            throw new BusinessException("信用分必须在0-100之间");
        }
        
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId)
                .eq(UserInfo::getDeleted, 0));
        
        if (userInfo == null) {
            throw new BusinessException("用户不存在");
        }
        
        userInfo.setCreditScore(creditScore);
        userInfo.setUpdateTime(LocalDateTime.now());
        
        return updateById(userInfo);
    }

    /**
     * 更新用户等级
     *
     * @param userId    用户ID
     * @param userLevel 用户等级
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserLevel(Long userId, Integer userLevel) {
        if (userLevel < 0 || userLevel > 3) {
            throw new BusinessException("用户等级必须在0-3之间");
        }
        
        UserInfo userInfo = getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserId, userId)
                .eq(UserInfo::getDeleted, 0));
        
        if (userInfo == null) {
            throw new BusinessException("用户不存在");
        }
        
        userInfo.setUserLevel(userLevel);
        userInfo.setUpdateTime(LocalDateTime.now());
        
        return updateById(userInfo);
    }

    /**
     * 根据积分更新用户等级
     *
     * @param userInfo 用户信息
     */
    private void updateUserLevelByPoints(UserInfo userInfo) {
        int points = userInfo.getPoints();
        
        if (points >= 10000) {
            userInfo.setUserLevel(3); // 钻石用户
        } else if (points >= 5000) {
            userInfo.setUserLevel(2); // 黄金用户
        } else if (points >= 1000) {
            userInfo.setUserLevel(1); // VIP用户
        }
    }

    /**
     * 将实体对象转换为VO对象
     *
     * @param userInfo 用户信息实体
     * @return 用户信息VO
     */
    private UserInfoVO convertToVO(UserInfo userInfo) {
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(userInfo, userInfoVO);
        
        // 设置性别名称
        if (userInfo.getGender() != null) {
            switch (userInfo.getGender()) {
                case 1:
                    userInfoVO.setGenderName("男");
                    break;
                case 2:
                    userInfoVO.setGenderName("女");
                    break;
                default:
                    userInfoVO.setGenderName("未知");
            }
        }
        
        // 设置用户等级名称
        if (userInfo.getUserLevel() != null) {
            switch (userInfo.getUserLevel()) {
                case 1:
                    userInfoVO.setUserLevelName("VIP用户");
                    break;
                case 2:
                    userInfoVO.setUserLevelName("黄金用户");
                    break;
                case 3:
                    userInfoVO.setUserLevelName("钻石用户");
                    break;
                default:
                    userInfoVO.setUserLevelName("普通用户");
            }
        }
        
        return userInfoVO;
    }
} 